package com.wangmeng.book.dao;


import com.wangmeng.book.entity.BookDoc;
import org.hibernate.AnnotationException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * User: 王猛
 * Date: 13-7-25
 */
@Transactional
public class BaseDaoSupport implements IBaseDao {
    protected SessionFactory sessionFactory;

    public <T> T getEntityById(Class<T> cls, Serializable id) {
        Session session = sessionFactory.openSession();
        Object entity = session.get(cls, id);
        session.close();
        return (T) entity;
    }

    public void saveEntity(Object entity) {
        if (entity != null) {
            Session session = sessionFactory.openSession();
            session.saveOrUpdate(entity);
            session.flush();
            session.close();
        }
    }

    public void deleteEntity(Object entity) {
        if (entity != null) {
            if(entity instanceof BookDoc){
                BookDoc bd = (BookDoc)entity;
                try {
                    bd.setName(new String(bd.getName().getBytes(),"UTF-8"));
                    bd.setAuthor(new String(bd.getAuthor().getBytes(),"UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            Session session = sessionFactory.openSession();
            session.delete(entity);
            session.flush();
            session.close();
        }
    }

    public <T> List<T> listEntityByCondition(Class<T> cls, String condition, Object[] params) {
        Session session = sessionFactory.openSession();
        String sql = "from " + cls.getName() + " where 1=1 " + (condition != null ? condition : "");
        Query query = session.createQuery(sql);
        if (params != null) {
            for (int p = 0; p < params.length; p++) {
                query.setParameter(p, params[p]);
            }
        }
        List<T> result = query.list();
        session.close();
        return result;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
}
